<template>
  <div>
    <AUpload
      v-model:file-list="fileList"
      :action="impUrl"
      draggable
      :headers="{
        token: getToken()!,
        'tenant-id': userInfo.tenantId
      }"
      :on-before-remove="uploadBeforeRemove"
      @error="uploadError"
      @success="uploadSuccess"
      @change="uploadChange"
    >
      <template #upload-button>
        <AButton type="outline" status="normal">上传文件</AButton>
      </template>
    </AUpload>
  </div>
</template>

<script lang="ts" setup>
import { FileItem, Message } from '@arco-design/web-vue'
import { useUserStore } from '@renderer/store'
import { FileListType } from '@renderer/types/global'
import { getToken } from '@renderer/utils/auth'

type Props = {
  attachFiles: FileListType[]
}
const props = withDefaults(defineProps<Props>(), {
  attachFiles: () => []
})
const emits = defineEmits(['update:attachFiles'])
const impUrl = 'http://47.122.115.90:8000/admin-api/infra/file/upload'
const userInfo = useUserStore().localUserInfo
const fileList = ref<FileItem[]>([])

watch(
  () => props.attachFiles,
  (newValue) => {
    fileList.value = newValue.map((item) => {
      return {
        uid: item.fileId,
        status: 'done',
        percent: 100,
        url: item.fileUrl,
        name: item.fileName
      }
    })
  }
)

const uploadSuccess = (fileItem: FileItem) => {
  if (fileItem.response.result == 0) {
    Message.error(fileItem.response.msg)
  } else {
    const newFile: FileListType = {
      fileId: fileItem.response.data.fileId,
      fileName: fileItem.response.data.fileName,
      fileUrl: fileItem.response.data.fileUrl
    }
    emits('update:attachFiles', [...props.attachFiles, newFile])
    Message.success('上传成功')
  }
}
const uploadError = () => {
  Message.error('系统错误，请联系管理人员')
}
const uploadBeforeRemove = (fileItem: FileItem): Promise<boolean> => {
  return new Promise((resolve) => {
    const newFileList = props.attachFiles.filter((item) => item.fileId != fileItem.uid)
    emits('update:attachFiles', newFileList)
    resolve(true)
  })
}
const uploadChange = () => {}
</script>
<style scoped></style>
